package com.lqb.webScaffold.handlers;

import com.lqb.webScaffold.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

@Component
public class UserHandler implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if( token!=null ) token = token.replace("Bearer ","");
        if ( !isTokenRequired(request) && extractToken(token)==null ) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"会话过期，请重新登录！\"}");
            return false;
        }
        return true;
    }

    private String extractToken(String authorization) {//验证token是否过期
        String userId = jwtUtils.parseToken(authorization);
        return userId;
    }

    private boolean isTokenRequired(HttpServletRequest request) {
        String uri = request.getRequestURI();
        ArrayList<String> list = new ArrayList<>();
        list.add("/login");
        list.add("/websocket");
        for (String s : list) if (uri.endsWith(s)) return true;
        return false;
    }

}
